package cn.hinglo.website.controller;

import cn.hinglo.baseservice.annotation.IgnoreToken;
import cn.hinglo.baseservice.base.BaseController;
import cn.hinglo.common.entity.Result;
import cn.hinglo.website.bean.model.User;
import cn.hinglo.website.config.constant.SysConstant;
import cn.hinglo.website.service.LoginService;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;


/**
 * @createTime: 2018/9/21 13:02
 * @author: HingLo
 * @description: 登录相关操作
 */
@RestController
@RequestMapping("/u")
@Validated
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录操作
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     */
    @PostMapping("login")
    @IgnoreToken
    public Result login(@NotNull(message = "用户名不能为空") String username, @NotNull(message = "密码不能为空") String password, String code) {
        // if (validateCaptcha(code)) {
        // return error("验证码错误");
        // }
        Result result = loginService.login(username, password);
        // 登录成功后将数据放到session中
        if (result.getCode() == SysConstant.SUCCESS_CODE) {
            User user = (User) result.getData();
            setSessionAttr(SysConstant.LOGIN, user);
        }
        return result;
    }

    /***
     * 请求验证码
     */
    @GetMapping("code")
    public void code(HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 15);
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();
        setSessionAttr("checkCode", code);
        lineCaptcha.write(response.getOutputStream());
    }

    /***
     * 校验验证码
     *
     * @param code code
     * @return 返回验证码验证结果
     */
    private boolean validateCaptcha(String code) {
        if (StrUtil.isBlank(code)) {
            return true;
        } else {
            return code.equals(getSessionAttr("checkCode"));
        }
    }
}
